package cn.wolfcode.trip.app.web.controller;

import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.query.TravelQueryObject;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

//操作用户资源的控制
@RestController
@RequestMapping("/users")
public class UserController{
    @Autowired
    private IUserService userService;
    @Autowired
    private ITravelService travelService;

    /*
        查询某个用户的所有游记
        动作:GET
        资源:/users/{authorId}/travels
        参数:
     */
    @GetMapping("/{authorId}/travels")
    public Object queryTravels(TravelQueryObject qo) {
        //设置最后更新时间降序排列
        qo.setOrderBy("t.lastUpdateTime desc");
        PageInfo<Travel> pageInfo = travelService.queryTravels(qo);
        return pageInfo;
    }

    /*
        用户更新接口
        资源:/users/{id}
        动作:PUT
        参数:nickName=xx&place=xx&headImgUrl=xx&
             gender=xx&coverImgUrl=xx&sign=xx
     */
    @PutMapping("/{id}")
    public Object update(User u) {
        JSONResult result = new JSONResult();
        userService.update(u);
        result.setObj(u);
        return result;
    }

    /*
        用户注册:
        资源:/users
        动作:POST
        参数:email=xx&nickName=xx&password=xx
     */
    @PostMapping
    public Object regist(User u) {
        JSONResult result = new JSONResult();
        try {
            userService.regist(u);
            result.setObj(u); //设置返回的数据
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }
}
